import { useRoutes } from "react-router-dom";
import { lazy, Suspense, useMemo } from "react";
import MainLayout from "@/layout/MainLayout";
import UserLayout from "@/layout/UserLayout";
import { RoutersProps } from "./interface";
import { useSelector } from "react-redux";
import type { StateType } from "@/store";
import NotFound from "@/views/NotFound";
import Login from "@/views/Login";
import Register from "@/views/Register";

const initialRoutes: RoutersProps[] = [
  {
    path: "/user",
    name: "user",
    element: <UserLayout />,
    children: [
      {
        path: "register",
        name: "register",
        element: <Register />,
      },
      {
        path: "login",
        name: "login",
        element: <Login />,
      },
    ],
  },
];
// 静态导入映射
const componentMap = {
  Home: lazy(() => import("@/views/Home/index.tsx")),
  Menu: lazy(() => import("@/views/System/Menu/index.tsx")),
  // 其他组件映射
};

function generateRoutes(data: RoutersProps[]): RoutersProps[] {
  return data.map((item) => {
    if (item.component === "Layout") {
      return {
        path: "/",
        element: <MainLayout />,
        children: item.children ? generateRoutes(item.children) : [],
      };
    } else {
      if (item.meta.type == 2) {
        const comPath = item.component;
        const LazyCom = componentMap[comPath];
        // const LazyCom = lazy(() => import(`@/views${comPath}/index.tsx`));
        return {
          path: item.path,
          children: item.children ? generateRoutes(item.children) : [],
          element: (
            <Suspense
              fallback={
                <div
                  style={{
                    position: "absolute",
                    left: "50%",
                    top: "50%",
                  }}>
                  loading...
                </div>
              }>
              <LazyCom />
            </Suspense>
          ),
        };
      } else {
        return {
          path: item.path,
          children: item.children ? generateRoutes(item.children) : [],
        };
      }
    }
  });
}

const Router = () => {
  const menus = useSelector<StateType>((state) => state.user.userInfo.menus);
  const dynamicRoutes = useMemo(() => generateRoutes(menus), [menus]);

  const routes = useRoutes([
    ...initialRoutes,
    ...dynamicRoutes,
    { path: "*", element: <NotFound /> },
  ]);

  return routes;
};

export { Router };
